<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="../js/vue.min.js" charset="UTF-8"></script>
		<script src="https://unpkg.com/axios/dist/axios.min.js" charset="utf-8"></script>
		<script src="../js/rd.js" charset="UTF-8"></script>
		<title></title>
	</head>
	<body>
		<div id="vm">
			<button id="btn_json" @click="savejson">转化食品json</button>
		</div>
	</body>
</html>
<script>
	
	var post = function(getdata, callback){
		let params = new URLSearchParams();
		console.log(getdata);
		params.append('sql', getdata);
		axios.post("http://101.200.201.27/adm/kkdata/kap/postdatas.php", params, {headers: {'content-type': 'application/x-www-form-urlencoded'}}).then(function(r){
			console.log(r);
			callback(r.data);
		}).catch(function(e){
			console.log(e);
			callback(e)
		})
	}
	
	var vm = new Vue({
		el: '#vm',
		data: {
			foods_id: [],  // 用于保存未加json的所有 f_id 列表
			sort: 0,		// 用于指示foods_id的下标
			cur_id: 2,  // 用于保存当前的 f_id   
			jsons: {},  // 用于保存当前构造的json
			compo: [],  // 用于保存营养元素表
			d: {
				compo: "select * from kk_food.compo",
				foods: "select f_id from kk_food.foods where JSON is null",
				getfood: "select * from kk_food.foods where f_id = ",
				savejson: "update kk_food.foods set JSON = '$json' where f_id = ",
			}
		},
		methods: {
			// 对单一食材操作，cur_id指定id，然后button绑定此函数
			savejson: function(callback){
				let that = this;
				post(this.d['getfood'] + this.cur_id, function(r){
					console.log(r)
					let json = [];
					for(let i in that.compo){
						let compo = that.compo[i];
						if(r[0][compo.code]){  // 先判断该营养元素是否有值，为空或为0，则json中不生成该条目
							let c = {};
							for(let j in compo){
								c[j] = compo[j]
							}
							c.value = r[0][compo.code];
							json.push(c);
						}
					}
					post(that.d['savejson'].replace(/\$json/g, JSON.stringify(json)) + that.cur_id, function(r){
						console.log(r);
						callback()
					})
				})
			},
			// 对多食材操作，
			savejsons: function(){
				this.sort ++;
				if(this.sort < this.foods_id.length){
					this.cur_id = this.foods_id[this.sort]
					this.savejson(this.savejsons);
				}
				
			}
			
		},
		mounted: function(){
			let that = this;
			post(this.d['compo'], function(r){
				that.compo = r;
			})
			post(this.d['foods'], function(r){
				that.foods_id = r;
			})
		}
	})
</script>
